package top.yueyazhui.mysql_audit_log.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class ShellUtil {

    @Value("${yueyazhui.server.host}")
    private String HOST;
    @Value("${yueyazhui.server.username}")
    private String USERNAME;
    @Value("${yueyazhui.server.password}")
    private String PASSWORD;
    @Value("${yueyazhui.server.db-audit-log-path}")
    private String FILEPATH;
    private String FILENAME = "mysql-audit.json";

    /**
     * 连接 MySQL 所在的服务器，用 shell 脚本查询审计日志
     * @param count 审计日志的条数
     * @param params 模糊搜索关键词
     * @return
     */
    public Map<String, Object> getAuditLog(Integer count, String[] params) {
        String cmd = "tail -n " + count + " " + FILEPATH + FILENAME;
        for (String param : params) {
            cmd = cmd + " | grep '" + param + "'";
        }
        try {
            Map<String, Object> map = new HashMap<>();
            Connection connection = new Connection(HOST);
            connection.connect();
            boolean authenticate = connection.authenticateWithPassword(USERNAME, PASSWORD);
            if (!authenticate) {
                throw new RuntimeException("服务器认证失败");
            }
            Session session = connection.openSession();
            session.execCommand(cmd);
            InputStream stdout = new StreamGobbler(session.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            int rowCount = 0;
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                rowCount++;
                sb.append(line).append(",");
            }
            stdout.close();
            session.close();
            connection.close();
            map.put("count", rowCount);
            String jsonStr = sb.toString();
            if (!("[".equals(jsonStr))) {
                jsonStr = jsonStr.substring(0, jsonStr.length() - 1) + "]";
                map.put("list", jsonStr);
            } else {
                map.put("list", "[]");
            }
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
